<?php
namespace app\models;

use app\models\Admin;
use app\models\Model;
use app\models\AuthRole;
use Yii;
use yii\helpers\ArrayHelper;

/**
 * Change password model
 *
 * @property integer $id
 * @property string $username
 * @property string $password
 * @property string $repassword
 * @property string $oldpassword
 */
class ChangePassword extends Model
{
    public $password;
    public $repassword;
    public $oldpassword;
    private $_user = false;

    /**
      * @inheritdoc
      */
    public function rules()
    {
        return [

            [['password', 'repassword', 'oldpassword'], 'required'],

            ['repassword', 'compare', 'compareAttribute' => 'password'],

            [['password', 'repassword', 'oldpassword'], 'string', 'min' => 5, 'max' => 30],

            ['oldpassword', 'validateOldPassword'],
        ];
    }


    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {

        return
            [
                'oldpassword' => '旧密码',
                'password' => '新密码',
                'repassword' => '确认新密码',
            ];
    }



    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validateOldPassword($attribute, $params)
    {
        if (!$this->hasErrors()) {
            $user = $this->getUser();
            if (!$user || !$user->validatePassword($this->oldpassword)) {
                $this->addError($attribute, '密码不正确！');
            }
        }
    }

    /**
     * Finds user by [[username]]
     *
     * @return Admin|null
     */
    public function getUser()
    {
        if ($this->_user === false) {
            $this->_user = Admin::findOne([
                'username' => Yii::$app->user->identity->username,
                'status' => Admin::STATUS_ACTIVE,
            ]);
        }

        return $this->_user;
    }

    public function save()
    {
        $model = $this->getUser();
        $model->setPassword($this->password);
        $model->updated_at = date('Y-m-d H:i:s',time());
        $model->generateAuthKey();
        return $model->save();
    }

}
